package com.ruoyi.master.config.redis;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.system.api.domain.WxText;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.stream.RecordId;
import org.springframework.data.redis.connection.stream.StreamRecords;
import org.springframework.data.redis.connection.stream.StringRecord;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;

@Service
@Slf4j
public class RedisPushService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisStreamConfig redisStreamConfig;

    @Autowired
    private ObjectMapper objectMapper;

    public void push(String msg){
        // 创建消息记录, 以及指定stream
        StringRecord stringRecord = StreamRecords.string(Collections.singletonMap("data", msg)).withStreamKey(redisStreamConfig.getStream());
        // 将消息添加至消息队列中
        this.stringRedisTemplate.opsForStream().add(stringRecord);
        log.info("{}已发送消息:{}",redisStreamConfig.getStream(),msg);
    }

    public String push(WxText msg){
        // 使用 Jackson 将 WxText 对象序列化为 JSON 字符串
        String jsonMsg = null;
        try {
            jsonMsg = objectMapper.writeValueAsString(msg);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        // 创建消息记录, 以及指定stream
        StringRecord stringRecord = StreamRecords.string(Collections.singletonMap("data", jsonMsg)).withStreamKey(redisStreamConfig.getStream());
        // 将消息添加至消息队列中
        RecordId rs = this.stringRedisTemplate.opsForStream().add(stringRecord);
        log.info("{}已写入redis消息队列:{}",redisStreamConfig.getStream(),msg);
        return rs.getValue();
    }
}
